import { useMutationObserver } from '@peng_kai/kit/libs/vueuse';
import dayjs from 'dayjs';
import { i18n, localeManager } from './i18n';
import { defineStartup } from '~/utils/defines';
import 'dayjs/locale/zh-cn';

function updateDayjsLocale() {
  const isZh = document.documentElement.lang.startsWith('zh');
  dayjs.locale(isZh ? 'zh-cn' : 'en');
}

export default defineStartup(async (app, hooks) => {
  const locale = localeManager.locale = i18n.global.locale.value = localeManager.locale;
  const fallbackLocale = i18n.global.fallbackLocale.value.toString();
  const localeMsg = await localeManager.loadLocaleMessage(locale);
  const fallbackLocaleMsg = await localeManager.loadLocaleMessage(fallbackLocale);
  localeMsg && i18n.global.setLocaleMessage(locale, localeMsg);
  fallbackLocaleMsg && i18n.global.setLocaleMessage(fallbackLocale, fallbackLocaleMsg);

  hooks.onMount(() => {
    useMutationObserver(document.documentElement, updateDayjsLocale, { attributeFilter: ['lang'] });
    updateDayjsLocale();
  });

  app.use(i18n);
});
